<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>分配权限</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 权限列表 -->
    <el-card>
      <el-tree :data="treeData" :props="defaultProps" 
        node-key="id"
        show-checkbox
        :default-checked-keys="defaultKeys"
        ref="treeRef"
        default-expand-all
      ></el-tree>

      <div class="footer">
        <el-button type="primary" @click="handleRightUpdate">保存</el-button>
        <el-button  plain @click="handleClear">清空</el-button>
      </div>
    </el-card>
  </div>
</template>
<script>
import {getRights} from '../../../api/right'
import {updateRight} from '../../../api/role'
export default {
  created(){
    this.getAllRights()
  },
  data(){
    return{
      roleId:0,
      treeData:[],
      defaultProps: {
          children: 'children',
          label: 'authName'
      },
      defaultKeys:[]
    }
  },
  methods:{
    // 递归获取权限数组
    treeToArr(node,arr){
      if(node.children && node.children.length>0){
        node.children.forEach(ele => {
          this.treeToArr(ele,arr)
        });
      }else{ //叶子节点
        arr.push(node.id)
      }
    },
    // 获取所有权限
    async getAllRights(){
      console.log(this.$route.params);
      this.roleId = this.$route.params.id
      const arr = []
      this.treeToArr(this.$route.params,arr)
      this.defaultKeys = arr
      try {
        const res = await getRights('tree')
        this.treeData = res.data
      } catch (err) {
        console.log(err);
      }
    },
    // 提交修改权限
    async handleRightUpdate(){
      const HalfCheckedKeys = this.$refs.treeRef.getHalfCheckedKeys()
      const checkedKeys =this.$refs.treeRef.getCheckedKeys()
      const rids = checkedKeys.concat(HalfCheckedKeys).join(',')
      // console.log(rids);
      try {
        const res = await updateRight(this.roleId,{
          rids
        })
        this.$message({
          type:'success',
          message:res.meta.msg
        })
        this.$router.back()
      } catch (err) {
        console.log(err);
      }
    },
    // 清空选中的权限
    handleClear(){
      this.$refs.treeRef.setCheckedKeys([])
    }
  }
}
</script>
<style scoped>
.footer{
  text-align: center;
  margin-top: 20px;
}
</style>